/*
	解法：每次处理2k + 末尾不足2k的部分 + reverse 前k个
	为什么：无
	时间复杂度：O(n)，空间复杂度：O(1)
 */

#include <iostream>
#include <string>
#include <algorithm> // for reverse

using namespace std;

class Solution
{
public:
	string reverseStr(string s, int k)
	{
		int n = static_cast<int>(s.size());
		
		// 每次处理完整的 2k 块
		for (int i = 0; i + 2 * k <= n; i += 2 * k)
		{
			reverse(s.begin() + i, s.begin() + i + k);
		}
		
		// 处理末尾不足 2k 的部分
		int tailLength = n % (2 * k);
		int tailBegin = n - tailLength;
		
		if (tailLength < k)
		{
			reverse(s.begin() + tailBegin, s.end()); // 全部反转
		}
		else
		{
			reverse(s.begin() + tailBegin, s.begin() + tailBegin + k); // 只反转前 k 个
		}
		
		return s;
	}
};


int main()
{
	Solution solution;
	
	// 示例 1
	string s1 = "abcdefg";
	int k1 = 2;
	string result1 = solution.reverseStr(s1, k1);
	cout << "输入：s = \"abcdefg\", k = 2" << endl;
	cout << "输出：" << result1 << endl << endl;
	
	// 示例 2
	string s2 = "abcd";
	int k2 = 2;
	string result2 = solution.reverseStr(s2, k2);
	cout << "输入：s = \"abcd\", k = 2" << endl;
	cout << "输出：" << result2 << endl;
	
	return 0;
}


